﻿using Dynamics.NAV.Metro.Common;
using Dynamics.NAV.Metro.Data;
using Okra.Core;
using Okra.Navigation;
using System;
using System.Collections.Generic;
using System.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace Dynamics.NAV.Metro.Pages.ItemDetail
{
    public class ItemDetailViewModel : BindableBase, IActivatable<NavItem, string>
    {
        private NavItem _selectedItem;
        private IList<NavItem> _Items;

        public ItemDetailViewModel()
        {
            this.GoBackCommand = new DelegateCommand(GoBack);

            NavItemDataSource navDataSource = new NavItemDataSource();
            this.Items = navDataSource.GetItems();
        }

        [ImportingConstructor]
        public ItemDetailViewModel(INavItemDataSource navItemDataSource)
        {
            this.GoBackCommand = new DelegateCommand(GoBack);
            this.Items = navItemDataSource.GetItems();
        }

        
        [Import]
        public INavigationManager NavigationManager { get; set; }

        public ICommand GoBackCommand { get; private set; }

        public bool CanGoBack
        {
            get { return NavigationManager.CanGoBack; }
        }

        public void GoBack()
        {
            NavigationManager.GoBack();
        }

        public void Activate(NavItem arguments, string state)
        {
            if (arguments == null)
                this.SelectedItem = this.Items.FirstOrDefault();
            else
                this.SelectedItem = arguments;
        }

        public string SaveState()
        {
            return null;
        }

        public NavItem SelectedItem
        {
            get 
            {
                if (this._selectedItem == null)
                {
                    this.SelectedItem = this.Items.FirstOrDefault();
                }

                return this._selectedItem; 
            }
            set
            {
                if (_selectedItem != value)
                {
                    _selectedItem = value;
                    OnPropertyChanged("SelectedItem");
                }
            }
        }

        public IList<NavItem> Items
        {
            get
            {
                return _Items;
            }
            set
            {
                if (_Items != value)
                {
                    _Items = value;
                    OnPropertyChanged("Items");
                }
            }
        }
    }
}
